#pragma once
#include <iostream>
#include <string>
#include <sstream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "util.hpp"
const std::string sep = "\r\n";
const std::string default_home = "./wwwroot";
const std::string label = "index.html";
const std::string heml_404 = "wwwroot/404.html";

class Request
{
public:
    Request()
    {
    }
    ~Request()
    {
    }

    // 解析请求
    void parse()
    {
        reqline = Util::parseOneLine(inbuffer, sep);
        if (reqline.empty())
            return;
        std::cout << "line: " << reqline << std::endl;
        //  根据？把字符串分割 左边：path   右边：parameter
        std::stringstream ss(reqline);
        ss >> method >> url >> httpversion;

        path = default_home;
        path += url;
        if (path[path.size() - 1] == '/')
        {
            path += label;
        }

        auto pos = path.rfind(".");
        if (pos == std::string::npos)
            suffix = ".html";
        else
            suffix = path.substr(pos);

        // 5. 得到资源的大小
        struct stat st;
        if(stat(path.c_str(), &st) == 0)
        {
            size = st.st_size;
        }
        else
        {
            stat(heml_404.c_str(), &st); //一定会调用成功
            size = st.st_size;
        }
    }

public:
    std::string inbuffer;

    std::string reqline;
    // std::string reqheader;
    // std::string reqbody;

    std::string method;
    std::string url;
    std::string httpversion;

    std::string path;
    std::string suffix;
    std::string parm;
    int size;
};

class Response
{
public:
    std::string outbuffer;
};